<template>
  <div
    v-if="lItem && lItem.list && lItem.list.length"
    class="drawerTemplateData-view-item drawerTemplateInput"
  >
    <div
      v-for="(sItem, sKey) in lItem.list"
      :key="sKey"
      :class="[
        'drawerTemplateData-view-item-input',
        'drawerTemplateData-view-item-input-margin',
        `${props.isBox ? 'drawerTemplateData-view-item-input-position' : ''}`,
        `${
          sItem.inputType === 'readWriteSlider' ? 'drawerTemplateData-view-item-input-width100' : ''
        }`,
      ]"
      :style="{
        top: sItem.top || 0,
        left: sItem.left || 0,
      }"
    >
      <div
        v-if="!sItem.hidden"
        :class="['flex', `${sItem.visibilityHidden ? 'visibilityHidden' : ''}`]"
      >
        <div
          v-if="lItem.showLabel && !sItem.inputType.includes('btn')"
          class="drawerTemplateData-view-item-input drawerTemplateData-view-item-label"
        >
          {{ getLabelFn(sItem) }}
        </div>
        <div v-if="sItem.inputType === 'read'" class="drawerTemplateData-view-item-input-read">
          <div class="drawerTemplateData-view-item-input-read-val">
            {{ getReadFn(sItem) }}
          </div>
        </div>
        <div
          v-if="
            sItem.inputType === 'write' ||
            sItem.inputType === 'confirmWrite' ||
            sItem.inputType === 'readWrite'
          "
          class="drawerTemplateData-view-item-input-write"
        >
          <InputNumber
            :class="[
              'drawerTemplateData-view-item-input-write-number',
              `${
                sItem.styleType === 'redBgColor'
                  ? 'drawerTemplateData-view-item-input-write-number-red'
                  : ''
              }`,
            ]"
            :min="sItem.min || 0"
            :max="sItem.max || 999999999"
            :iconSize="28"
            :showReduce="false"
            :showAdd="false"
            :defaultValue="sItem.inputType === 'readWrite' ? getReadFn(sItem) : sItem.value"
            :precision="sItem.precision || precision || 2"
            :onUpdateValue="
              (val) => {
                inputUpdateFn(val, sItem, lItem.list);
              }
            "
            :timer="
              sItem.blurChange || sItem.inputType === 'confirmWrite'
                ? null
                : sItem.inputType === 'write' || sItem.inputType === 'readWrite'
                ? virtualKeyboard
                  ? null
                  : intervalNum
                : null
            "
            :focus="
              (e) => {
                inputFocusFn(e, sItem, lItem.list);
              }
            "
            :blur="
              (e) => {
                inputBlurFn(e, sItem, lItem.list);
              }
            "
            @timeChange="writeFn(sItem, lItem.list)"
          />

          <n-button
            v-if="sItem.inputType === 'confirmWrite'"
            :class="[
              'drawerTemplateData-view-item-input-write-number-confirm',
              `${
                sItem.styleType === 'whiteBgColor'
                  ? 'drawerTemplateData-view-item-input-btn-white'
                  : ''
              }`,
              `${
                sItem.styleType === 'redBtnBgColor'
                  ? 'drawerTemplateData-view-item-input-btn-red'
                  : ''
              }`,
            ]"
            type="primary"
            @click="btnClickFn(sItem, lItem.list)"
            @mousedown="btnClickFn(sItem, lItem.list, 'mousedown')"
            @mouseup="btnClickFn(sItem, lItem.list, 'mouseup')"
            @mouseleave="btnMouseLeaveFn(sItem, lItem.list)"
          >
            {{ $t('common.button.primary') }}
          </n-button>
        </div>

        <div
          v-if="
            sItem.inputType === 'btn' ||
            sItem.inputType === 'btnBool' ||
            sItem.inputType === 'btnText' ||
            sItem.inputType === 'btnDrawer' ||
            sItem.inputType === 'btnOpenModal' ||
            sItem.inputType === 'btnOtherOperate' ||
            sItem.inputType === 'btnBoolBit'
          "
          class="drawerTemplateData-view-item-input-btn"
        >
          <n-progress
            v-if="sItem.showProgress"
            class="drawerTemplateData-view-item-input-btn-progress"
            type="line"
            :percentage="sItem.progressNum || num / 10"
            :indicator-placement="'inside'"
            processing
            :color="'#307AFA'"
          />
          <n-button
            :class="[
              `${
                sItem.styleType === 'whiteBgColor'
                  ? 'drawerTemplateData-view-item-input-btn-white'
                  : ''
              }`,
              `${
                sItem.styleType === 'redBtnBgColor'
                  ? 'drawerTemplateData-view-item-input-btn-red'
                  : ''
              }`,
              `${
                sItem.btnActive
                  ? 'drawerTemplateData-view-item-input-btn-true'
                  : sItem.inputType === 'btnBool'
                  ? sItem.value
                    ? 'drawerTemplateData-view-item-input-btn-true'
                    : ''
                  : ''
              }`,
            ]"
            type="primary"
            @click="btnClickFn(sItem, lItem.list)"
            @mousedown="btnClickFn(sItem, lItem.list, 'mousedown')"
            @mouseup="btnClickFn(sItem, lItem.list, 'mouseup')"
            @touchstart="btnClickFn(sItem, lItem.list, 'touchstart')"
            @touchend="btnClickFn(sItem, lItem.list, 'touchend')"
            @mouseleave="btnMouseLeaveFn(sItem, lItem.list)"
          >
            <n-icon
              v-if="sItem.showIcon && sItem.value"
              :component="CheckmarkCircle"
              color="rgb(82, 197, 112)"
              :size="18"
            />
            {{ getLabelFn(sItem) }}
          </n-button>
        </div>

        <div
          v-if="sItem.inputType === 'btnBoolImg'"
          class="drawerTemplateData-view-item-input-btn drawerTemplateData-view-item-input-btn-img"
        >
          <img
            :src="setImgSrcFn(getReadFn(sItem), sItem)"
            :alt="getLabelFn(sItem)"
            @click="btnClickFn(sItem, lItem.list)"
            @mousedown="btnClickFn(sItem, lItem.list, 'mousedown')"
            @mouseup="btnClickFn(sItem, lItem.list, 'mouseup')"
            @mouseleave="btnMouseLeaveFn(sItem, lItem.list)"
          />
        </div>

        <div
          v-if="sItem.inputType === 'readWriteSlider'"
          class="drawerTemplateData-view-item-input-slider"
        >
          <n-slider
            v-model:value="sItem.value"
            show-tooltip
            :step="1"
            :min="sItem.sliderMin || 0"
            :max="sItem.sliderMax || 100"
            class="slider-view"
            :onUpdateValue="
              (val) => {
                inputUpdateFn(val, sItem, lItem.list);
              }
            "
          />
        </div>

        <div
          v-if="sItem.inputType === 'lengSelect' || sItem.inputType === 'lengSelectBit'"
          class="drawerTemplateData-view-item-input-write-number"
        >
          <n-select
            v-model:value="sItem.value"
            :options="lengOptionsList"
            :on-update:value="
              (val) => {
                sItem.value = val;

                updateLengSelectValueFn && updateLengSelectValueFn(val);

                writeFn(sItem, lItem.list);
              }
            "
          />
          <!-- <n-slider
            v-model:value="sItem.value"
            show-tooltip
            :step="1"
            :min="sItem.min || 0"
            :max="sItem.max || 100"
            class="slider-view"
            :onUpdateValue="
              val => {
                inputUpdateFn(val, sItem, lItem.list);
              }
            "
          /> -->
        </div>

        <div
          v-if="sItem.inputType === 'textBool' && getLabelFn(sItem) !== '-'"
          class="drawerTemplateData-view-item-input-write-text"
        >
          {{ getLabelFn(sItem) }}
        </div>

        <div
          v-if="sItem.inputType === 'text'"
          class="drawerTemplateData-view-item-input-write-text"
        >
          {{ getTextFn(sItem) }}
        </div>

        <div
          v-if="sItem.inputType === null"
          class="drawerTemplateData-view-item-input-width100px"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="DrawerTemplateInput">
  import InputNumber from './../InputNumber.vue';
  import { useMixins } from '@/hooks/useMixins';
  import { storage } from '@/utils/Storage';
  // import { filterWriteObjFn } from '@/utils/dfModbus/data';
  // import { filterFinsWriteObjFn } from '@/utils/dfFins/data';
  import { useUserStore } from '@/store/modules/user';
  import { CheckmarkCircle } from '@vicons/ionicons5';
  import { cloneDeep } from 'lodash';
  import { getComputedValFn } from './../../options/utils';
  // import { factoryName } from '@/utils/dataOptions/options';

  type Props = {
    data?: any;
    isBox?: boolean;
  };

  // const chooseItem: any = inject('chooseItem', null);

  // const updateMaterialParamFn: any = inject('updateMaterialParamFn', null);

  const connectType = inject('connectType', null);

  const materialParamList: any = inject('materialParamList', []);

  const props = withDefaults(defineProps<Props>(), {
    data: () => null,
    isBox: () => false,
  });

  const lengOptionsList = inject('lengOptionsList', []);

  // console.log(lengOptionsList)

  const intervalNum = 2000;

  const userStore = useUserStore();

  const virtualKeyboard = computed(() => userStore.virtualKeyboard);

  const message = window['$message'];

  const provitClickFn: any = inject('provitClickFn', () => null);

  const lItem: any = ref(null);

  const { language } = useMixins();

  // const modbusData: any = inject('modbusData');

  const modbusNewData: any = inject('modbusNewData', ref({}));

  const openDrawerTemplateModalFn: any = inject('openDrawerTemplateModalFn');

  const adjustingOptions: any = inject('adjustingOptions', null);

  const lengSelectValue: any = inject('lengSelectValue', null);

  const updateLengSelectValueFn: any = inject('updateLengSelectValueFn', null);

  let precision = 1;

  if (adjustingOptions) {
    const { precision: aPrecision = null } = adjustingOptions;

    if (aPrecision !== null) {
      precision = aPrecision;
    }
  }

  const getReadFn = (item) => {
    // 获取读取数据方法

    if (item) {
      const {
        inputType = null,
        isFocus = false,
        defaultValGetFunId = null,
        hiddenTrueFunIdList = [],
        hiddenFalseFunIdList = [],
        lengFunIdObj = null,
        value = null,
        precision: iPrecision = null,
        defaultWriteValGetLengFunIdObj = null,
        decimalPlaces = 0,
        defaultValGetOrderField = null,
        valGetMaterialParamParamCode = null,
        bit = null,
      } = item;

      if (lengFunIdObj && lengSelectValue && lengSelectValue.value) {
        // 动态funId 根据所选楞别动态化
        item.funId = lengFunIdObj[lengSelectValue.value] || null;
      }

      let newValue: any = value || 0;

      // if (item.funId === 'trimming') {
      //   console.log(item.value);

      //   console.log(newValue);
      // }

      if (item.funId) {
        // newValue =
        //   modbusData.value.find(mItem => mItem.funId === item.funId)?.value ||
        //   newValue ||
        //   0;

        newValue = [undefined, null].includes(modbusNewData.value[item.funId])
          ? newValue || 0
          : modbusNewData.value[item.funId];

        // 小数位
        if (decimalPlaces !== 0) {
          let zero = '';

          for (let i = 0; i < decimalPlaces; i++) {
            zero += '0';
          }

          const num = Number(1 + zero);

          if (!isNaN(num)) {
            newValue = Number(newValue / num).toFixed(
              iPrecision !== null ? iPrecision : precision || 2
            );
          }
        }

        // console.log(modbusNewData);

        // if (item.funId === 'rnteringGroove') {

        //   if (newValue === '1') {
        //     console.log(newValue)
        //   }
        // }
      }

      if (defaultWriteValGetLengFunIdObj) {
        // 根据楞别把标准值写入设置值 当楞别变化，设置值重新写入变化楞别的标准值
        // console.log(defaultWriteValGetLengFunIdObj)
        if (
          lengSelectValue &&
          lengSelectValue.value &&
          (lengSelectValue.value !== item.defaultWriteValGetLengVal ||
            !item.isWriteDefaultWriteValGetLengFunId)
        ) {
          const wFunId = defaultWriteValGetLengFunIdObj[lengSelectValue.value] || null;

          if (wFunId) {
            // const wVal =
            //   modbusData.value.find(mItem => mItem.funId === wFunId)?.value || 0;

            const wVal = modbusNewData.value[wFunId] || 0;

            item.defaultWriteValGetLengVal = lengSelectValue.value;

            writeFn({
              funId: item.funId,
              value: wVal,
            });
          }
        }

        item.isWriteDefaultWriteValGetLengFunId = true;
      }

      // if (item.funId === 'dieCutCardboard') {
      //   console.log(newValue)

      //   // console.log(iPrecision)
      // }

      if (inputType === 'btnBool' || inputType === 'btnBoolImg' || inputType === 'textBool') {
        const { list = [] } = toRaw(lItem.value);

        if (defaultValGetFunId) {
          // 设置显示的默认值
          // newValue =
          //   modbusData.value.find(item => item.funId === defaultValGetFunId)
          //     ?.value || 0;

          newValue = modbusNewData.value[defaultValGetFunId] || 0;
        }

        // if (connectType !== 's7') {
        //   // if(item.funId === "slottingPreloadingWheelGapAdd"){
        //   //   console.log(item.value)
        //   // }
        //   // console.log(newValue)
        //   newValue = Number(newValue) === 1 ? true : false;
        // }

        newValue =
          Object.prototype.toString.call(newValue) === '[object Boolean]'
            ? newValue
            : Number(newValue) === 1
            ? true
            : false;

        item.value = newValue;

        const hiddenFunIdList = toRaw(
          (newValue ? hiddenTrueFunIdList : hiddenFalseFunIdList) || []
        );

        // if (item.funId === '1ColorZeroSwitching') {
        //   console.log(newValue)
        //   console.log(item)

        //   console.log(hiddenFalseFunIdList)
        // }

        // console.log(item)

        if (hiddenFunIdList && hiddenFunIdList.length && list && list.length) {
          // 动态展示funId列表
          for (const dItem of list) {
            dItem.hidden = hiddenFunIdList.includes(dItem.funId);
          }

          lItem.value.list = list;
        } else if (!hiddenFunIdList?.length) {
          for (const dItem of list) {
            dItem.hidden = false;
          }
        }

        return newValue;
      } else if (inputType === 'btnBoolBit') {
        item.valueArr = newValue;

        newValue = toRaw(newValue)[bit] || 0;

        newValue =
          Object.prototype.toString.call(newValue) === '[object Boolean]'
            ? newValue
            : Number(newValue) === 1
            ? true
            : false;

        item.value = newValue;

        return newValue;
      } else if (inputType === 'readWrite') {
        if (isFocus) {
          // 是否获取焦点，获取焦点不覆盖正在输入的值
          return item.value;
        } else {
          // 小数位
          // if (decimalPlaces !== 0) {
          //   let zero = '';

          //   for (let i = 0; i < decimalPlaces; i++) {
          //     zero += '0';
          //   }

          //   const num = Number(1 + zero);

          //   if (!isNaN(num)) {
          //     item.value = Number(item.value / num).toFixed(
          //       iPrecision !== null ? iPrecision : precision || 2
          //     );
          //   }
          // } else {
          //   item.value = newValue;
          // }

          // console.log(item.value);
          item.value = newValue;

          return newValue;
        }
      } else if (inputType === 'read' && defaultValGetOrderField) {
        return item.value;
      } else if (
        inputType === 'read' &&
        valGetMaterialParamParamCode &&
        materialParamList &&
        materialParamList.value &&
        materialParamList.value.length
      ) {
        let mVal: any = 0;

        materialParamList.value.every((mItem) => {
          if (mItem.paramCode === valGetMaterialParamParamCode) {
            item.value = mItem.sr;

            mVal = mItem.sr || 0;

            return false;
          }

          return true;
        });

        // 小数位
        if (decimalPlaces !== 0) {
          let zero = '';

          for (let i = 0; i < decimalPlaces; i++) {
            zero += '0';
          }

          const num = Number(1 + zero);

          if (!isNaN(num)) {
            mVal = Number(mVal / num).toFixed(iPrecision !== null ? iPrecision : precision || 2);
          }
        }

        return Number(mVal)
          .toFixed(precision || 2)
          .toString();
      } else {
        const value = Number(newValue).toFixed(iPrecision !== null ? iPrecision : precision || 2);

        item.value = value;

        return value;
      }
    }

    return Number(0)
      .toFixed(precision || 2)
      .toString();
  };

  const getLabelFn = (item) => {
    // 获取label文字方法

    if (item) {
      const {
        labelZh = null,
        labelEn = null,
        labelRu = null,
        labelTrueZh = null,
        labelTrueEn = null,
        labelTrueRu = null,
        labelFalseZh = null,
        labelFalseEn = null,
        labelFalseRu = null,
        inputType = null,
        textObj = null,
      } = item;

      let itemVal = getReadFn(item) as any;

      // if(item.funId === 'equipmentStatusGet'){
      //   console.log(itemVal)
      // }

      // console.log(item)

      if (inputType === 'btnBool' || inputType === 'textBool' || inputType === 'btnBoolBit') {
        // if (item.funId === 'rnteringGroove') {
        //   console.log(itemVal)
        // }

        if (Object.prototype.toString.call(itemVal) === '[object Boolean]') {
          itemVal = itemVal ? '1' : '0';
        }

        // if (connectType === 's7' || connectType==='fins') {
        //   itemVal = itemVal ? '1' : '0';
        // }

        if (itemVal) {
          return language.value === 'zh'
            ? Number(itemVal)
              ? labelTrueZh || labelTrueEn || labelTrueRu || labelZh || labelEn || labelRu || '-'
              : labelFalseZh || labelFalseEn || labelFalseRu || labelZh || labelEn || labelRu || '-'
            : language.value === 'ru'
            ? Number(itemVal)
              ? labelTrueRu || labelTrueZh || labelTrueEn || labelRu || labelEn || labelZh || '-'
              : labelFalseRu || labelFalseZh || labelFalseEn || labelRu || labelEn || labelZh || '-'
            : Number(itemVal)
            ? labelTrueEn || labelTrueZh || labelTrueRu || labelEn || labelZh || labelRu || '-'
            : labelFalseEn || labelFalseZh || labelFalseRu || labelEn || labelZh || labelRu || '-';
        } else {
          return language.value === 'zh'
            ? labelZh || labelEn || labelRu
            : language.value === 'ru'
            ? labelRu || labelZh || labelEn
            : labelEn || labelZh || labelRu;
        }
      }

      if (inputType === 'btnText' && textObj) {
        // textObj对象 不同值展示不同的文字
        // console.log(itemVal)
        let text =
          language.value === 'zh'
            ? labelZh || labelEn || labelRu
            : language.value === 'ru'
            ? labelRu || labelZh || labelRu
            : labelEn || labelZh || labelRu;

        for (const i in textObj) {
          if (Number(i) === Number(itemVal)) {
            text =
              language.value === 'zh'
                ? textObj[i]['labelZh'] || textObj[i]['labelEn'] || textObj[i]['labelRu'] || text
                : language.value === 'ru'
                ? textObj[i]['labelRu'] || textObj[i]['labelEn'] || textObj[i]['labelZh'] || text
                : textObj[i]['labelEn'] || textObj[i]['labelZh'] || textObj[i]['labelRu'] || text;
          }
        }

        if (Number(itemVal) === 0) {
          item.btnActive = false;

          item.progressNum = 0;

          item.showProgress = false;
        } else {
          item.btnActive = true;

          item.showProgress = true;

          item.progressNum = Number(itemVal) * 20;
        }

        // item.btnActive = Number(itemVal) === 0 ? false : true;

        return text;
      }

      if (labelZh || labelEn) {
        return language.value === 'zh'
          ? labelZh || labelEn || labelRu
          : language.value === 'ru'
          ? labelRu || labelZh || labelEn
          : labelEn || labelZh || labelRu;
      }
    }

    return '-';
  };

  const getTextFn = (item) => {
    // 获取label文字方法

    if (item) {
      const { textZh = null, textEn = null, textRu = null } = item;

      if (textZh || textEn) {
        return language.value === 'zh'
          ? textZh || textEn || textRu
          : language.value === 'ru'
          ? textRu || textZh || textEn
          : textEn || textZh || textRu;
      }
    }

    return '-';
  };

  const setDataFn = (obj = null) => {
    // console.log(obj);
    if (obj) {
      const data: any = toRaw(obj);

      lItem.value = data;
    }
  };

  const getLocalByFunId = (funId = null) => {
    // 获取localstorage中的值

    let val = 0;

    if (funId) {
      const writeData = storage.get('writeData');

      if (writeData && writeData.length) {
        writeData.every((item) => {
          if (item.funId === funId) {
            val = item.value || 0;

            return false;
          }

          return true;
        });
      }
    }

    return val;
  };

  const setLocalByFunId = (funId = null, val = 0) => {
    // 设置localstorage中的值

    if (funId) {
      const writeData = storage.get('writeData');

      if (writeData && writeData.length) {
        const obj = writeData.find((item) => item.funId === funId);

        if (obj) {
          obj.value = val;
        } else {
          writeData.push({ funId, value: val });
        }

        storage.set('writeData', writeData);
      } else {
        storage.set('writeData', [{ funId, value: val }]);
      }
    }
  };

  let updateSetBaoFunIdTime: any = null;

  const saveMachineParamFn: any = inject('saveMachineParamFn', null);

  const writeFn = async (item, list: any = [], fn: any = null, isUpdateSetBaoFunId = false) => {
    // 写入方法
    try {
      if (item) {
        const newItem = cloneDeep(item);

        const {
          updateClear = false,
          value = null,
          updateSetVal = null,
          updateSetFunId = null,
          inputType = null,
          writeVal = null,
          lengFunIdObj = null,
          notWrite = false,
          writeUpdateListFunIdObjList = null,
          decimalPlaces = null,
          updateSetBaoFunId = null,
          clickInputType = null,
          saveMachineParam = false,
          valueArr = null,
          bit = null,
        } = newItem;

        console.log(item);

        if (writeUpdateListFunIdObjList && writeUpdateListFunIdObjList.length) {
          // 写入更新其他funId的值
          for (const uItem of writeUpdateListFunIdObjList) {
            const { funId: wFunId = null, computedValInListObj = null } = uItem;

            if (wFunId && computedValInListObj) {
              const lObj = list.find((lItem) => lItem.funId === wFunId);

              if (lObj) {
                lObj.value = getComputedValFn(computedValInListObj, list);
              }
            }
          }

          // const { funId: wFunId = null, computedValInListObj = null } =
          //   writeUpdateListFunIdObj;

          // if (wFunId && computedValInListObj) {
          //   const lObj = list.find(lItem => lItem.funId === wFunId);

          //   if (lObj) {
          //     lObj.value = getComputedValFn(computedValInListObj, list);
          //   }
          // }
        }

        if (notWrite) {
          // 不写入
          return;
        }

        // console.log(item);

        if (lengFunIdObj && lengSelectValue && lengSelectValue.value) {
          // 根据选择的楞别写入funId
          newItem.funId = lengFunIdObj[lengSelectValue.value] || null;
        }

        // console.log(newItem);

        if (newItem.funId) {
          // console.log(obj)

          if (provitClickFn && provitClickFn.value) {
            let newVal = value;

            // console.log(newVal);

            // console.log(inputType);

            if (
              inputType === 'btnBool' ||
              inputType === 'btnBoolImg' ||
              clickInputType === 'btnBool' ||
              inputType === 'btnBoolBit'
            ) {
              if (writeVal !== null) {
                newVal = writeVal ? 1 : 0;
              } else {
                newVal = Number(newVal) ? 0 : 1;
              }

              if (inputType === 'btnBoolBit') {
                if (valueArr && valueArr.length && bit !== null) {
                  valueArr[bit] = newVal.toString();

                  newVal = valueArr;
                }
              }
            } else if (inputType === 'btnText') {
              // 寄存器类型按钮
              newVal = writeVal;
            } else if (inputType === 'write' || inputType === 'readWrite') {
              // 小数位
              if (decimalPlaces !== 0) {
                let zero = '';

                for (let i = 0; i < decimalPlaces; i++) {
                  zero += '0';
                }

                const num = Number(1 + zero);

                if (!isNaN(num)) {
                  newVal = newVal * num;
                }
              }
            } else if (inputType === 'lengSelectBit') {
              newVal = writeVal;
            }

            if (newVal !== null) {
              // console.log({
              //   ...obj,
              //   value: newVal,
              //   addr: obj.offsetId
              // });
              if (connectType === 'webSocket') {
                const params = {};

                params[newItem.funId] = newVal;

                console.log(params);

                provitClickFn.value(params);
              } else {
                // console.log(22);
                provitClickFn.value({
                  funId: newItem.funId,
                  value: newVal,
                  inputType,
                });
              }

              fn && fn();
            }
          }

          if (updateSetFunId && updateSetVal !== null) {
            // 更新后设置其他funId的值

            setTimeout(() => {
              if (updateSetFunId && list && list.length) {
                list.every((lItem) => {
                  if (lItem.funId === updateSetFunId) {
                    lItem.value = updateSetVal;

                    return false;
                  }

                  return true;
                });
              } else {
                item.value = updateSetVal;
              }
            }, intervalNum);
          }

          if (isUpdateSetBaoFunId && updateSetBaoFunId) {
            if (updateSetBaoFunIdTime) {
              clearTimeout(updateSetBaoFunIdTime);

              updateSetBaoFunIdTime = null;
            }

            provitClickFn.value({
              funId: updateSetBaoFunId,
              value: 1,
              inputType: 'btnBool',
            });

            updateSetBaoFunIdTime = setTimeout(() => {
              provitClickFn.value({
                funId: updateSetBaoFunId,
                value: 0,
                inputType: 'btnBool',
              });
            }, intervalNum);
          }

          if (isUpdateSetBaoFunId && saveMachineParam && saveMachineParamFn) {
            saveMachineParamFn();
            // await saveZhMachineParamFn(
            //   modbusNewData,
            //   chooseItem,
            //   updateMaterialParamFn,
            //   Number(noSelectColor.value) ? 9999999 : colorSetId,
            //   getSaveParametersList
            // );
          }

          if (updateClear) {
            // 更新后更新值

            updateClearFn(item, list);
          }
        } else {
          message.error(!item ? '无写入数据' : '无funId');
        }
      }
    } catch (e) {
      console.log(e);
    }
  };

  const clearIsFocusTimeFn = (item) => {
    // 清除获取焦点定时器
    if (item && item.isFocusTime) {
      clearTimeout(item.isFocusTime);

      item.isFocusTime = null;
    }
  };

  const updateClearFn = (item, list) => {
    // 写入后清除方法
    if (item) {
      const {
        updateClear = false,
        updateClearFunId = null,
        defaultValGetLocal = null,
        funId = null,
      } = item;

      if (item.updateClearTime) {
        clearTimeout(item.updateClearTime);

        item.updateClearTime = null;
      }

      if (updateClear) {
        item.updateClearTime = setTimeout(() => {
          if (updateClearFunId && list && list.length) {
            list.every((lItem) => {
              if (lItem.funId === updateClearFunId) {
                if (!lItem.isFocus) {
                  lItem.value = lItem.defaultValGetLocal
                    ? getLocalByFunId(lItem.funId)
                    : lItem.defaultVal || 0;
                }

                return false;
              }

              return true;
            });
          } else {
            if (!item.isFocus) {
              item.value = defaultValGetLocal ? getLocalByFunId(funId) : item.defaultVal || 0;
            }
          }

          clearTimeout(item.updateClearTime);

          item.updateClearTime = null;
        }, intervalNum + 1);
      }
    }
  };

  const inputBlurFn = async (_e, item, list, isWrite = false) => {
    // 失去焦点事件
    if (item) {
      const {
        inputType = null,
        blurChange = false,
        updateClear = false,
        // funId = null, value = null
      } = item;

      if (inputType) {
        if (
          ((inputType === 'write' || inputType === 'readWrite') && (blurChange || isWrite)) ||
          inputType === 'readWriteSlider'
        ) {
          // const data = toRaw(item);
          const { writeOtherFunIdList = null } = item;

          if (writeOtherFunIdList && writeOtherFunIdList.length) {
            // 触发写入其他funId列表的值

            const params = {};

            for (let i = 0; i < writeOtherFunIdList.length; i++) {
              const {
                funId = null,
                writeVal = null,
                computedValInListObj = null,
                decimalPlaces = null,
              } = writeOtherFunIdList[i];

              let writeValue = writeVal || item.value;

              if (computedValInListObj) {
                writeValue = getComputedValFn(computedValInListObj, list);
              }

              if (decimalPlaces !== 0) {
                let zero = '';

                for (let i = 0; i < decimalPlaces; i++) {
                  zero += '0';
                }

                const num = Number(1 + zero);

                if (!isNaN(num)) {
                  writeValue = writeValue * num;
                }
              }

              if (connectType === 'webSocket') {
                params[funId] = writeValue;
              } else {
                writeFn({
                  funId,
                  value: writeValue,
                });
              }
            }

            if (connectType === 'webSocket' && provitClickFn && provitClickFn.value) {
              if (JSON.stringify(params) !== '{}') {
                console.log(params);
                provitClickFn.value(params);
              } else {
                message.error('请检查下发参数，下发参数为空');
              }
            }

            if (updateClear) {
              // 写入后清除
              updateClearFn(item, list);
            }
          } else {
            writeFn(
              item,
              list
              // , () => {
              //   if (factoryName === 'dongfang' && updateMaterialParamFn && chooseItem && chooseItem.value && funId && value!==null) {
              //     const { version = null, materialCode = null, machineCode = null,orderStatusId=null, actualDebugCompleteTime=null} = chooseItem.value;

              //     if (version && materialCode && machineCode && orderStatusId === '30' && !actualDebugCompleteTime) {
              //       console.log('保存参数');

              //       const { decimalPlaces = null } = item;

              //       let newVal = value;

              //       if (decimalPlaces !== 0) {
              //         let zero = '';

              //         for (let i = 0; i < decimalPlaces; i++) {
              //           zero += '0';
              //         }

              //         const num = Number(1 + zero);

              //         if (!isNaN(num)) {
              //           newVal = newVal * num;
              //         }
              //       }

              //       updateMaterialParamFn([{
              //         machineCode,
              //         materialCode,
              //         version,
              //         paramCode:funId,
              //         sr:newVal
              //       }])
              //     }
              //   }
              // }
            );
          }
        }

        clearIsFocusTimeFn(item);

        item.isFocusTime = setTimeout(() => {
          item.isFocus = false;
        }, intervalNum);
      }
    }
  };

  const inputFocusFn = (_e, item, _list) => {
    // 获取焦点事件
    if (item.inputType === 'readWrite') {
      if (getReadFn(item) !== item.value) {
        item.value = getReadFn(item);
      }
    }

    clearIsFocusTimeFn(item);

    console.log(item);

    item.isFocus = true;
  };

  let readWriteSliderTime: any = null;

  const inputUpdateFn = async (val, item, list) => {
    if (val !== null && item) {
      const { funId = null, valSetLocal = false, inputType = null, sliderTime = 1000 } = item;

      item.value = val.value || val || 0;

      // console.log(item.value);

      // await inputBlurFn(null,item,list)

      if ((inputType === 'write' || inputType === 'readWrite') && virtualKeyboard.value) {
        inputFocusFn(null, item, list);

        await inputBlurFn(null, item, list, true);
      } else {
        if (inputType === 'readWriteSlider') {
          item.isFocus = true;

          if (readWriteSliderTime) {
            clearTimeout(readWriteSliderTime);

            readWriteSliderTime = null;
          }

          readWriteSliderTime = setTimeout(async () => {
            await inputBlurFn(null, item, list, true);
          }, sliderTime);
        }
      }

      if (funId && valSetLocal) {
        setLocalByFunId(funId, val.value || 0);
      }
    }
    // console.log(item);
  };

  const openDrawerFn: any = inject('openDrawerFn', null);

  let time: any = null;

  const num: any = ref(0);

  let isClick: any = false;

  const delayedBtnClickFn = (item, list, type, clickTime) => {
    // 延迟触发写入事件
    item.showProgress = true;

    num.value = 0;

    if (time) {
      clearInterval(time);

      time = null;
    }

    time = setInterval(() => {
      // console.log(num)
      if (num.value >= clickTime) {
        btnClickFn({ ...item, clickTime: 0 }, list, type);

        // console.log(11111)

        clearInterval(time);

        time = null;

        isClick = true;

        item.showProgress = false;
      } else {
        num.value += 100;
      }
    }, 100);
  };

  const btnMouseLeaveFn = (item, list) => {
    // 鼠标移开目标事件

    if (time) {
      clearInterval(time);

      time = null;
    }

    num.value = 0;

    item.showProgress = false;

    item.btnActive = false;

    if (isClick) {
      btnClickFn({ ...item, clickTime: 0 }, list, 'mouseup');

      isClick = false;
    }
  };

  const btnNextDrawerTypeClickFn: any = inject('btnNextDrawerTypeClickFn', null);

  const btnClickFn = async (item, list, type = 'click') => {
    // 按钮点击事件
    console.log(type);
    if (item) {
      const {
        funId = null,
        writeFunId = null,
        inputType = null,
        drawerType = null,
        clickType = null,
        clickTime = null,
        modalType = null,
        modalTypeTabName = null,
        writeOtherFunIdList = null,
        nextDrawerType = null,
        endTime = null,
      } = item;

      if (
        !clickType &&
        (type === 'mouseup' || type === 'mousedown' || type === 'touchstart' || type === 'touchend')
      ) {
        return;
      }

      if (clickType && type === 'click') {
        return;
      }

      if (inputType === 'btnOpenModal') {
        // 打开弹窗类型
        if (modalType && openDrawerTemplateModalFn && adjustingOptions) {
          // console.log(adjustingOptions[modalType]);
          openDrawerTemplateModalFn(adjustingOptions[modalType], modalTypeTabName);
        }

        return;
      }

      if (type.includes('mouse') && item.isTouch) {
        if (type === 'mouseup') {
          item.isTouch = false;
        }

        return;
      }

      if (type.includes('touch')) {
        item.isTouch = true;
      }

      if (clickTime) {
        // 延迟触发
        if (type === 'mousedown' || type === 'touchstart') {
          delayedBtnClickFn(item, list, type, clickTime);

          isClick = false;

          item.btnActive = true;

          return;
        }

        if (type === 'mouseup' || type === 'touchend') {
          if (time) {
            clearInterval(time);

            time = null;
          }

          if (num.value < clickTime) {
            num.value = 0;

            // 展示进度条
            item.showProgress = false;

            item.btnActive = false;

            return;
          }

          // 展示进度条
          item.showProgress = false;

          num.value = 0;
        }
      }

      // console.log(type);

      if (inputType === 'btnDrawer' && drawerType && openDrawerFn) {
        // 打开其他抽屉
        openDrawerFn(drawerType);

        return;
      }

      if (
        inputType === 'btnDrawer' &&
        nextDrawerType &&
        btnNextDrawerTypeClickFn &&
        clickType !== 'startAndEnd'
      ) {
        btnNextDrawerTypeClickFn(nextDrawerType);

        return;
      }

      if (inputType === 'btnOtherOperate') {
        // 其他操作
        if (writeOtherFunIdList && writeOtherFunIdList.length) {
          // 写入其他funId的值
          const params = {};

          let params1: any = null;

          for (let i = 0; i < writeOtherFunIdList.length; i++) {
            const {
              funId = null,
              writeValGetLengFunIdObj = null,
              clickType = null,
              writeVal = 1,
              inputType = 'btnBool',
              computedValInListObj = null,
              writeValGetFunId = null,
              writeValGetListFunId = null,
              clickInputType = null,
            } = writeOtherFunIdList[i];

            if (clickType === 'startAndEnd') {
              // 一键归位

              if (connectType === 'webSocket') {
                params[funId] = writeVal;

                if (!params1) {
                  params1 = {};
                }

                params1[funId] = writeVal === 1 ? true : false;
              } else {
                writeFn(
                  {
                    funId,
                    value: writeVal,
                    inputType: clickInputType || inputType,
                    fn: writeFn({
                      funId,
                      value: writeVal === 1 ? 0 : 1,
                      inputType: clickInputType || inputType,
                    }),
                  },
                  [],
                  null,
                  true
                );
              }
            } else {
              if (funId) {
                if (writeValGetLengFunIdObj) {
                  // 同步楞别标准值
                  // console.log(writeValGetLengFunIdObj)
                  if (lengSelectValue && lengSelectValue.value) {
                    const lengFunId = writeValGetLengFunIdObj[lengSelectValue.value];

                    if (lengFunId) {
                      // const value =
                      //   modbusData.value.find(item => item.funId === lengFunId)
                      //     ?.value || 0;

                      // const value = modbusData.value.find(item => item.funId === lengFunId)
                      //     ?.value || 0;

                      const value = modbusNewData.value[lengFunId];

                      if (!value) {
                        console.log(lengFunId);
                      }

                      if (connectType === 'webSocket') {
                        params[funId] = value;
                      } else {
                        writeFn(
                          {
                            funId,
                            inputType,
                            value,
                          },
                          [],
                          null,
                          true
                        );
                      }
                    }
                  }
                } else if (computedValInListObj) {
                  // 通过其他funId进行计算

                  // console.log(funId)
                  // if(funId === 'slottingDESet'){
                  //   console.log(getComputedValFn(computedValInListObj, list));

                  //   // console.log(inputType);
                  // }

                  // console.log({
                  //   funId,
                  //   inputType,
                  //   value: getComputedValFn(computedValInListObj, list)
                  // });

                  const value = getComputedValFn(computedValInListObj, list);

                  if (connectType === 'webSocket') {
                    params[funId] = value;
                  } else {
                    writeFn(
                      {
                        funId,
                        inputType,
                        value,
                      },
                      [],
                      null,
                      true
                    );
                  }
                } else if (writeValGetFunId) {
                  // 写入其他funId的值

                  // const value =
                  //   modbusData.value.find(
                  //     mItem => mItem.funId === writeValGetFunId
                  //   )?.value || 0;

                  const value = modbusNewData.value[writeValGetFunId];

                  if (connectType === 'webSocket') {
                    params[funId] = value;
                  } else {
                    writeFn(
                      {
                        funId,
                        inputType,
                        value:
                          inputType === 'btnBool' ? (Number(value) === 1 ? true : false) : value,
                      },
                      [],
                      null,
                      true
                    );
                  }
                } else if (writeValGetListFunId) {
                  // 写入列表中其他funId的值
                  const value: any =
                    list.find((mItem) => mItem.funId === writeValGetListFunId)?.value || 0;

                  if (connectType === 'webSocket') {
                    params[funId] = inputType === 'btnBool' ? (Number(value) === 1 ? 1 : 0) : value;
                  } else {
                    writeFn(
                      {
                        funId,
                        inputType,
                        value:
                          inputType === 'btnBool' ? (Number(value) === 1 ? true : false) : value,
                      },
                      [],
                      null,
                      true
                    );
                  }
                } else {
                  // 正常写入
                  if (connectType === 'webSocket') {
                    if (inputType === 'btnBool') {
                      params[funId] = writeVal === 1 ? true : false;
                    } else {
                      params[funId] = writeVal;
                    }
                  } else {
                    writeFn(
                      {
                        funId,
                        inputType,
                        value: writeVal,
                        writeVal,
                      },
                      [],
                      null,
                      true
                    );
                  }
                }
              }
            }
          }

          if (connectType === 'webSocket' && provitClickFn && provitClickFn.value) {
            if (JSON.stringify(params) !== '{}') {
              provitClickFn.value(
                params,
                params1
                  ? () => {
                      provitClickFn.value(params1);
                    }
                  : null
              );
            } else {
              message.error('下发参数为空');
            }
          }
        }

        return;
      }

      if (writeFunId && list && list.length) {
        // 触发写入其他funId的值
        const writeItem = list.find((lItem) => lItem.funId === writeFunId);

        if (writeItem) {
          writeFn(writeItem, list);
        } else {
          message.error(`找不到writeFunId:${writeFunId}的写入数据`);
        }

        return;
      }

      if (funId) {
        if (clickType && clickType === 'startAndEnd') {
          // 鼠标按下写1离开写0
          switch (type) {
            case 'mousedown':
            case 'touchstart':
              isClick = true;

              item.btnActive = true;

              writeFn(item, list, null, true);

              break;
            case 'mouseup':
            case 'touchend':
              isClick = false;

              item.btnActive = false;

              console.log(endTime);

              if (endTime) {
                if (item.endTimeT) {
                  clearTimeout(item.endTimeT);

                  item.endTimeT = null;
                }

                item.endTimeT = setTimeout(() => {
                  writeFn({ ...item, writeVal: item.writeVal === 0 ? 1 : 0 }, list, null, false);

                  clearTimeout(item.endTimeT);

                  item.endTimeT = null;
                }, endTime);
              } else {
                writeFn({ ...item, writeVal: item.writeVal === 0 ? 1 : 0 }, list, null, false);
              }

              if (inputType === 'btnDrawer' && nextDrawerType && btnNextDrawerTypeClickFn) {
                btnNextDrawerTypeClickFn(nextDrawerType);
              }

              // writeFn({ ...item, writeVal: item.writeVal === 0 ? 1 : 0 }, list);

              break;
            default:
              break;
          }

          return;
        } else {
          // 普通正常写入
          writeFn(item, list, null, true);
        }
      } else {
        message.error('无funId');
      }
    }
  };

  const getDataFn = () => {
    return unref(lItem);
  };

  const interfaceImageList = inject('interfaceImageList', ref([]));

  const baseUrl = `http://${storage.get('host')}:3000/file/`;

  const setImgSrcFn = (val, item) => {
    if (item) {
      const { imgMapKey, img, imgTrue, imgFalse, imgTrueMapKey, imgFalseMapKey } = item;

      if (val) {
        if (imgTrueMapKey) {
          const obj = interfaceImageList.value.find((item) => item.imgCode === imgTrueMapKey);

          if (obj) {
            return `${baseUrl}${obj.imgUrl}`;
          } else if (imgMapKey) {
            const obj = interfaceImageList.value.find((item) => item.imgCode === imgMapKey);

            if (obj) {
              return `${baseUrl}${obj.imgUrl}`;
            } else if (imgTrue) {
              return imgTrue;
            } else {
              return img;
            }
          }
        } else if (imgTrue) {
          return imgTrue;
        } else if (imgMapKey) {
          const obj = interfaceImageList.value.find((item) => item.imgCode === imgMapKey);

          if (obj) {
            return `${baseUrl}${obj.imgUrl}`;
          } else {
            return img;
          }
        } else {
          return img;
        }
      } else {
        if (imgFalseMapKey) {
          const obj = interfaceImageList.value.find((item) => item.imgCode === imgFalseMapKey);

          if (obj) {
            return `${baseUrl}${obj.imgUrl}`;
          } else if (imgMapKey) {
            const obj = interfaceImageList.value.find((item) => item.imgCode === imgMapKey);

            if (obj) {
              return `${baseUrl}${obj.imgUrl}`;
            } else if (imgFalse) {
              return imgFalse;
            } else {
              return img;
            }
          }
        } else if (imgFalse) {
          return imgFalse;
        } else if (imgMapKey) {
          const obj = interfaceImageList.value.find((item) => item.imgCode === imgMapKey);

          if (obj) {
            return `${baseUrl}${obj.imgUrl}`;
          } else {
            return img;
          }
        } else {
          return img;
        }
      }

      return img;
    }
  };

  // const { data = null } = props;

  // if (data) {
  //   setDataFn(data);
  // }

  watch(
    props,
    () => {
      if (props && props.data) {
        setDataFn(props.data);
      }
      // valueNum.value = virtualKeyboard?props.defaultValue+'':props.defaultValue || null;
    },
    { deep: true, immediate: true }
  );

  defineExpose({ setDataFn, getDataFn });
</script>

<style lang="less">
  .drawerTemplateInput {
    display: flex;
    flex-wrap: wrap;

    .flex {
      display: flex;
      align-items: center;
      .drawerTemplateData-view-item-label {
        min-width: 60px;
        width: auto !important;
        // margin-right: 6px;
      }
    }

    .visibilityHidden {
      visibility: hidden;
    }
  }

  .drawerTemplateData-view-item-input-margin {
    margin: 0 12px 0 0;
  }

  .drawerTemplateData-view-item-input-width100px {
    width: 100px;
  }

  .drawerTemplateData {
    .drawerTemplateData-view-box {
      .drawerTemplateData-view-btn {
        padding: 0;
        .drawerTemplateInput {
          padding: 0;
          border: 0;
        }
      }

      .drawerTemplateData-view-item-input-position {
        position: absolute;
      }
    }

    .drawerTemplateData-view-btn {
      .drawerTemplateInput {
        width: 100%;
        justify-content: space-around;
      }
    }

    .drawerTemplateData-view-item-input-btn-img {
      img {
        display: block;
        width: 100px;
        cursor: pointer;
      }
    }

    .drawerTemplateData-view-item-input-width100 {
      width: 100%;
      .flex {
        width: 100%;
      }
    }

    .drawerTemplateData-view-item-input-btn-white {
      background: #fff !important;
      border: 1px solid #d4d6d9 !important;
      color: #222222 !important;
    }

    .drawerTemplateData-view-item-input-btn-red {
      background: linear-gradient(180deg, #edbfa3 11%, #307AFA 89%) !important;
    }

    .drawerTemplateData-view-item-input-slider {
      .slider-view {
        width: 100%;
      }
    }

    .drawerTemplateData-view-item-input-write-number-red {
      .n-input {
        background-color: #fff0f0;
      }
    }

    .drawerTemplateData-view-item-input-write-text {
      min-height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 100px;
    }
  }

  .drawerTemplateData-view-item-input-btn-true {
    background-color: #307AFA !important;
    .n-button__border {
      border-color: #307AFA !important;
    }

    // border-image: none !important;
    // color: #307AFA !important;
    // background: linear-gradient(146deg, #ffffff 5%, #dfd9d7 57%) !important;
    // border-image-source: linear-gradient(45deg, rgba(255, 106.00000128149986, 63.000000044703484, 1), rgba(255, 106.00000128149986, 63.000000044703484, 0))!important;
  }

  .drawerTemplateData-view-item-input-btn {
    position: relative;
  }

  .drawerTemplateData-view-item-input-btn-progress {
    position: absolute;
    top: -18px;
  }
</style>
